package services

import (
	"bsm/daos"
	"bsm/logger"
	"bsm/models"
	"fmt"
)

type SystemService interface {
	GetUsersWithPagination(page, limit int, keyword string) ([]models.WebUser, int64, error)
	GetSystemStats() (map[string]interface{}, error)
	GetAllSessions() ([]models.Session, error)
	GetUserSessions(userID string) ([]models.Session, error)
	GetActiveSessionsCount(userID string) (int, error)
	TerminateSession(sessionID string) error
	TerminateUserSessions(userID string) (int, error)
	GetProjects(orgCode string, designType int) ([]models.ProjectLite, error)

	SynchronizeUser() error
}

type systemServiceImpl struct {
	userDao    daos.UserDao
	designDao  daos.DesignDao
	sessionSvc RedisSessionService // 使用现有的会话服务接口
}

func NewSystemService(userDao daos.UserDao, designDao daos.DesignDao, sessionSvc RedisSessionService) SystemService {
	return &systemServiceImpl{
		userDao:    userDao,
		designDao:  designDao,
		sessionSvc: sessionSvc,
	}
}

// GetUsersWithPagination 获取用户列表（分页）
func (s *systemServiceImpl) GetUsersWithPagination(page, limit int, keyword string) ([]models.WebUser, int64, error) {

	pusers, total, err := s.userDao.GetUsersWithPagination(page, limit, keyword)
	if err != nil {
		logger.WithFields(map[string]interface{}{
			"layer":     "service",
			"operation": "GetUsersWithPagination",
		}).Errorf("GetUsersWithPagination: failed to get users: %v", err)
		return nil, 0, err
	}
	ucount := len(pusers)
	var wusers []models.WebUser
	var sessionCount int
	for i := 0; i < ucount; i++ {
		org, err := s.userDao.GetOrgByCode(pusers[i].OrgCode)
		if err != nil {
			logger.WithFields(map[string]interface{}{
				"layer":     "service",
				"operation": "GetUsersWithPagination",
			}).Errorf("GetUsersWithPagination: failed to get org: %v", err)

		} else {
			sessions, err := s.sessionSvc.GetUserSessions(pusers[i].UserID)
			if err != nil {
				logger.WithFields(map[string]interface{}{
					"layer":     "service",
					"operation": "GetUsersWithPagination",
				}).Errorf("GetUsersWithPagination: failed to get sessions: %v", err)
				sessionCount = 0
			} else {
				sessionCount = len(sessions)
			}
			var webUser models.WebUser
			webUser.ID = pusers[i].ID
			webUser.UserID = pusers[i].UserID
			webUser.UserName = pusers[i].UserName
			hasAdminRole, _ := s.userDao.CheckUserRole(pusers[i].UserID, models.UserRole_Admin)
			if hasAdminRole {
				webUser.UserType = 1
			} else {
				webUser.UserType = 0
			}
			webUser.OrgCode = pusers[i].OrgCode
			webUser.OrgLevel = org.OrgLevel
			webUser.OrgName = org.OrgName
			webUser.OrgPrefix = org.Prefix
			webUser.OrgFullName = org.FullName
			webUser.OrgLiteName = org.LiteName
			webUser.OrgInuse = org.OrgInuse
			webUser.CreatedAt = pusers[i].CreatedAt
			webUser.SessionCount = sessionCount
			webUser.IsActive = pusers[i].IsActive
			wusers = append(wusers, webUser)
		}
	}
	return wusers, total, nil
}

// GetSystemStats 获取系统统计
func (s *systemServiceImpl) GetSystemStats() (map[string]interface{}, error) {
	userCount, err := s.userDao.GetUserCount()
	if err != nil {
		logger.WithFields(map[string]interface{}{
			"layer":     "service",
			"operation": "GetSystemStats",
		}).Errorf("GetSystemStats: failed to get user count: %v", err)
		return nil, err
	}

	// 获取总活跃会话数（需要实现，或者通过其他方式统计）
	activeSessions := 0
	if s.sessionSvc != nil {
		// 这里可以遍历所有用户计算总会话数，或者维护一个全局计数器
		// 暂时返回0，你可以根据需要实现
		activeSessions, err = s.sessionSvc.GetAllActiveSessionsCount()
		if err != nil {
			logger.WithFields(map[string]interface{}{
				"layer":     "service",
				"operation": "GetSystemStats",
			}).Errorf("GetSystemStats: failed to get active session count: %v", err)
			return nil, err
		}
	}

	stats := map[string]interface{}{
		"user_count":      userCount,
		"active_sessions": activeSessions,
	}

	return stats, nil
}

// GetAllSessions 获取所有用户的会话列表
func (s *systemServiceImpl) GetAllSessions() ([]models.Session, error) {
	var allSessions []models.Session

	// 先获取所有用户
	users, _, err := s.userDao.GetUsersWithPagination(1, 1000, "") // 假设最多1000用户
	if err != nil {
		logger.WithFields(map[string]interface{}{
			"layer":     "service",
			"operation": "GetAllSessions",
		}).Errorf("GetAllSessions: failed to get users: %v", err)
		return nil, err
	}

	// 获取每个用户的会话
	for _, user := range users {
		if s.sessionSvc != nil {
			sessions, err := s.sessionSvc.GetUserSessions(user.UserID)
			if err == nil {
				allSessions = append(allSessions, sessions...)
			}
		}
	}

	return allSessions, nil
}

// GetUserSessions 获取指定用户的会话
func (s *systemServiceImpl) GetUserSessions(userID string) ([]models.Session, error) {
	if s.sessionSvc == nil {
		logger.WithFields(map[string]interface{}{
			"layer":     "service",
			"operation": "GetUserSessions",
		}).Errorf("GetUserSessions: failed to get user sessions for userID %s", userID)
		return nil, fmt.Errorf("session service not available")
	}
	return s.sessionSvc.GetUserSessions(userID)
}

// GetActiveSessionsCount 获取用户活跃会话数
func (s *systemServiceImpl) GetActiveSessionsCount(userID string) (int, error) {
	if s.sessionSvc == nil {
		logger.WithFields(map[string]interface{}{
			"layer":     "service",
			"operation": "GetActiveSessionsCount",
		}).Errorf("GetActiveSessionsCount: session service not available")
		return 0, fmt.Errorf("session service not available")
	}
	return s.sessionSvc.GetActiveSessionsCount(userID)
}

// TerminateSession 终止会话
func (s *systemServiceImpl) TerminateSession(sessionID string) error {
	if s.sessionSvc == nil {
		logger.WithFields(map[string]interface{}{
			"layer":     "service",
			"operation": "TerminateSession",
		}).Errorf("TerminateSession: session service not available")
		return fmt.Errorf("session service not available")
	}
	return s.sessionSvc.RemoveSession(sessionID)
}

// TerminateUserSessions 终止用户的所有会话
func (s *systemServiceImpl) TerminateUserSessions(userID string) (int, error) {
	if s.sessionSvc == nil {
		logger.WithFields(map[string]interface{}{
			"layer":     "service",
			"operation": "TerminateUserSessions",
		}).Errorf("TerminateUserSessions: session service not available")
		return 0, fmt.Errorf("session service not available")
	}

	// 获取用户的所有会话
	sessions, err := s.sessionSvc.GetUserSessions(userID)
	if err != nil {
		logger.WithFields(map[string]interface{}{
			"layer":     "service",
			"operation": "TerminateUserSessions",
		}).Errorf("TerminateUserSessions: failed to get user sessions for userID %s: %v", userID, err)
		return 0, err
	}

	// 终止所有会话
	terminated := 0
	for _, session := range sessions {
		if err := s.sessionSvc.RemoveSession(session.SessionID); err == nil {
			terminated++
		}
	}

	return terminated, nil
}

func (s *systemServiceImpl) SynchronizeUser() error {
	sysUsers, _, err := s.userDao.GetUsersWithPagination(1, 1000, "")
	if err != nil {
		return err
	}

	users, _, err := s.userDao.GetUsersWithPagination(1, 1000, "")
	if err != nil {
		return err
	}

	// 为本地用户创建快速查找的map
	usersMap := make(map[models.ProjectUser]bool)
	for _, item := range users {
		usersMap[item] = true
	}

	// 找出SYS_USER中有但本地用户中没有的元素
	var result []models.ProjectUser
	for _, item := range sysUsers {
		if !usersMap[item] {
			result = append(result, item)
		}
	}

	for _, user := range result {
		err := s.userDao.AddUser(&user) //只添加本地用户表中没有的原SYS_USER表中的用户
		if err != nil {
			return err
		}
	}
	return nil
}

func (s *systemServiceImpl) GetProjects(orgCode string, designType int) ([]models.ProjectLite, error) {
	var projects []models.ProjectLite
	projects, err := s.designDao.GetProjects(orgCode, designType)
	if err != nil {
		return nil, err
	}
	return projects, nil
}
